/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package yxt.push.org.androidpn.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.com.winning.ecare.activity.CostMzSelect;
import cn.com.winning.ecare.activity.HisNotificationDetail;
import cn.com.winning.ecare.activity.Login;
import cn.com.winning.ecare.activity.R;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.Utils;

/**
 * Activity for displaying the notification details view.
 * 
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class NotificationDetailsActivity extends Activity
{

	// private ListView lvGrid;
	private NotificationDetailsActivity oThis = this;
	private ImageButton menuButton;
	private ImageButton btclearall;
	private ImageButton btclearselected;
	private TextView hzxm;
	private Context context;
	Intent intent;
	private SQLiteDatabase mSQLiteDatabase = null;
	// MyAdapter adapter;
	private List<Map<String, Object>> grouplist = new ArrayList<Map<String, Object>>();
	private ListView groupListView;
	private GroupAdapter groupAdapter;

	List<Integer> listItemID = new ArrayList<Integer>();

	private static final String LOGTAG = LogUtil.makeLogTag(NotificationDetailsActivity.class);

	private String callbackActivityPackageName;

	private String callbackActivityClassName;

	private String accountname;

	private String mobilephone;

	private String hospitalcode;

	private List<String> ls = new ArrayList<String>();

	MyApplication application;

	private PopupWindow mPopupWindow;

	private RelativeLayout rl1, rl2,rl3;
	
	AlertDialog alertDialog = null;

	public NotificationDetailsActivity()
	{
	}

	private static final String data = "[{'name':'就诊前','type':'100'},{'name':'就诊中','type':'200'},{'name':'就诊后','type':'300'}]";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// setTitle("通知列表");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.push);
		// SharedPreferences sharedPrefs =
		// this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
		// Context.MODE_PRIVATE);
		// callbackActivityPackageName =
		// sharedPrefs.getString(Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, "");
		// callbackActivityClassName =
		// sharedPrefs.getString(Constants.CALLBACK_ACTIVITY_CLASS_NAME, "");
		application = (MyApplication) getApplication();
		if(application.getAccount() == null){
			Intent intent = new Intent();
			intent.setClass(oThis, Login.class);
			startActivity(intent);
			oThis.finish();
		}
		accountname = application.getAccount();
		mobilephone = application.getSjh();
		hospitalcode = application.getYydm();
		intent = getIntent();

		findViews();

		initData();

		// 为ListView填充数据
		setListViewData();

		// 设置ListItem点击事件
		setListeners();

		// View rootView = createView(notificationTitle, notificationMessage,
		// notificationUri);
		// setContentView(rootView);

	}

	public void findViews()
	{
		// lvGrid = (ListView) findViewById(R.id.lv_push);
		// btclose = (ImageButton) findViewById(R.id.close);
		// btclearall = (ImageButton) findViewById(R.id.clearall);
		btclearselected = (ImageButton) findViewById(R.id.clearselected);
		groupListView = (ListView) findViewById(R.id.lv_push);
		menuButton = (ImageButton) findViewById(R.id.menuButton);
		hzxm = (TextView) findViewById(R.id.hzxm);
		hzxm.setText(application.getHzxm() == null ? "" : application.getHzxm());
	}

	private void setListViewData()
	{
		// SimpleAdapter adapter = new SimpleAdapter(this, getData(),
		// R.layout.push_list,
		// new String[] { "title", "message", "time" }, new int[] {
		// R.id.title, R.id.message, R.id.time });
		// adapter = new MyAdapter(this, getData());
		// lvGrid.setAdapter(adapter);
		groupAdapter = new GroupAdapter();
		groupListView.setAdapter(groupAdapter);
		groupAdapter.notifyDataSetChanged();
	}

	private void setListeners()
	{
		// lvGrid.setOnItemClickListener(gridClick);
		// btclose.setOnClickListener(close);
		// btclearall.setOnClickListener(clearall);
		btclearselected.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// String str = "";
				// for (int i = 0; i < ls.size(); i++)
				// {
				// str += ls.get(i) + ",";
				// }
				// if (str.length() > 0)
				// {
				// str = str.substring(0, str.length() - 1);
				// }
				// Log.e("", str);
				// clear_selected(str);
				int pos[] = { -1, -1 }; // 保存当前坐标的数组
				int width, height;
				v.getLocationInWindow(pos); // 获取选中的 Item 在屏幕中的位置，
				DisplayMetrics dm = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(dm);
				height = dm.heightPixels;// 高度
				initPopuptWindow();
				if (height - pos[1] > mPopupWindow.getHeight())
				{
					mPopupWindow.showAsDropDown(v, -80, 0);
				}
				else
				{

					mPopupWindow.showAsDropDown(v, -80, -140);
				}
			}
		});
		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				oThis.onBackPressed();
			}
		});
	}

	private Button.OnClickListener close = new Button.OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			// TODO Auto-generated method stub
			NotificationDetailsActivity.this.finish();// 關閉當前
		}
	};
	//
	private Button.OnClickListener clearall = new Button.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			// TODO Auto-generated method stub
			savealltohistory();
			clear_all();
		}
	};

	// private Button.OnClickListener clearselected = new Button.OnClickListener()
	// {
	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	// listItemID.clear();
	// List<Map<String, Object>> list = getData();
	// for (int i = 0; i < adapter.mChecked.size(); i++) {
	// if (adapter.mChecked.get(i)) {
	// listItemID.add(Integer.parseInt((String) list.get(i).get("xh")));
	// }
	//
	// }
	// if (listItemID.size() > 0) {
	// for (int i = 0; i < listItemID.size(); i++) {
	// savetohistory(listItemID.get(i));
	// clear(listItemID.get(i));
	// }
	// print();
	// }
	// setListViewData();
	// }
	// };

	// 初始化菜单对话框
	private void initPopuptWindow()
	{
		LayoutInflater layoutInflater = LayoutInflater.from(oThis);
		View popupWindow = layoutInflater.inflate(R.layout.notification_popupwindow, null);
		mPopupWindow = new PopupWindow(popupWindow, DisplayUtil.dip2px(oThis, 160), DisplayUtil.dip2px(oThis, 240));
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.setOutsideTouchable(true);
		rl1 = (RelativeLayout) popupWindow.findViewById(R.id.seat_popupwindow_rl_01);// 换座
		rl2 = (RelativeLayout) popupWindow.findViewById(R.id.seat_popupwindow_rl_02);// 呼叫
		rl3 = (RelativeLayout) popupWindow.findViewById(R.id.seat_popupwindow_rl_03);// 呼叫
		rl1.setOnClickListener(new View.OnClickListener()// 换座
		{

			@Override
			public void onClick(View v)
			{
				mPopupWindow.dismiss();
				AlertDialog.Builder builder = new AlertDialog.Builder(oThis);

				builder.setTitle("提示");
				builder.setMessage("确定删除所选记录?");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						String str = "";
						for (int i = 0; i < ls.size(); i++)
						{
							str += ls.get(i) + ",";
						}
						if (str.length() > 0)
						{
							str = str.substring(0, str.length() - 1);
						}
						Log.e("", str);
						clear_selected(str);

					}
				});
				builder.setNegativeButton("取消", null);

				alertDialog = builder.create();
				alertDialog.show();
				
			}
		});

		rl2.setOnClickListener(new View.OnClickListener()// 呼叫
		{

			@Override
			public void onClick(View v)
			{
				mPopupWindow.dismiss();
				AlertDialog.Builder builder = new AlertDialog.Builder(oThis);

				builder.setTitle("提示");
				builder.setMessage("确定清空本地所有记录?");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						clear_all();

					}
				});
				builder.setNegativeButton("取消",null);

				alertDialog = builder.create();
				alertDialog.show();
				
			}
		});
		
		rl3.setOnClickListener(new View.OnClickListener()// 换座
		{

			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(oThis, HisNotificationDetail.class);
				startActivity(intent);
				mPopupWindow.dismiss();
			}
		});

	}

	public void clear_all()
	{
		String type = intent.getStringExtra(Constants.NOTIFICATION_TYPE);
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		String clearall = "delete from WX_PUSH where ((accountname ='" + accountname + "' and mobilephone='" + mobilephone
				+ "' and hospitalcode='" + hospitalcode + "' )or (accountname='winning' and mobilephone='winning' and hospitalcode='"
				+ hospitalcode + "'))";
		try
		{
			mSQLiteDatabase.execSQL(clearall);
			ls.clear();
			grouplist.clear();
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		mSQLiteDatabase.close();
		groupAdapter.notifyDataSetChanged();
	}

	public void clear_selected(String ids)
	{
		String type = intent.getStringExtra(Constants.NOTIFICATION_TYPE);
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		String clearall = "delete from WX_PUSH where xh in (" + ids + ")";
		try
		{
			mSQLiteDatabase.execSQL(clearall);
			ls.clear();
			grouplist.clear();
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		mSQLiteDatabase.close();
		initData();
		groupAdapter.notifyDataSetChanged();
	}

	public void clear(int xh)
	{
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		String clear = "delete from WX_PUSH where xh=" + xh;
		try
		{
			mSQLiteDatabase.execSQL(clear);
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		mSQLiteDatabase.close();
	}

	// ListView的Item点击监听事件
	private ListView.OnItemClickListener gridClick = new ListView.OnItemClickListener()
	{
		@SuppressWarnings("unchecked")
		public void onItemClick(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3)
		{
			// HashMap<String, Object> Item = (HashMap<String, Object>) arg0
			// .getAdapter().getItem(arg2);
			// savetohistory(Integer.parseInt((String) Item.get("xh")));
			// clear(Integer.parseInt((String) Item.get("xh")));
		};
	};

	private void initData()
	{
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		String createtable = " CREATE TABLE  if not exists WX_PUSH (xh  integer PRIMARY KEY autoincrement , "
				+ " title varchar(100)  ,message varchar(500)  ,apiKey varchar(100)  , "
				+ "uri varchar(100) ,time varchar(30) ,type varchar(30) ,sfbc varchar(30) ,"
				+ "memo varchar(100),accountname varchar(100),mobilephone varchar(100),hospitalcode varchar(100),senddate varchar(100),isshow varchar(100) DEFAULT '0')";
		try
		{
			mSQLiteDatabase.execSQL(createtable);
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}

		String select = " SELECT xh,title,message,time,type,senddate  FROM WX_PUSH where ((accountname ='" + accountname
				+ "' and mobilephone='" + mobilephone + "' and hospitalcode='" + hospitalcode
				+ "' )or (accountname='winning' and mobilephone='winning' and hospitalcode='" + hospitalcode + "'))  order by xh desc";

		Cursor cursor = mSQLiteDatabase.rawQuery(select, null);
		Map<String, Object> map = null;
		if (cursor != null && cursor.getCount() >= 0)
			while (cursor.moveToNext())
			{
				map = new HashMap<String, Object>();
				map.put("title", cursor.getString(cursor.getColumnIndex("title")));
				map.put("message",cursor.getString(cursor.getColumnIndex("message")));
				map.put("time", cursor.getString(cursor.getColumnIndex("time")));
				map.put("xh", cursor.getString(cursor.getColumnIndex("xh")));
				map.put("type", cursor.getString(cursor.getColumnIndex("type")));
				map.put("senddate", cursor.getString(cursor.getColumnIndex("senddate")));
				if (isJsonarray(map))
				{
					grouplist.add(map);
				}
				else
				{
					String clearall = "delete from WX_PUSH where xh =" + cursor.getInt(cursor.getColumnIndex("title"));
					mSQLiteDatabase.execSQL(clearall);
				}

			}
		String updatestate = " update WX_PUSH set isshow = '1' where ((accountname ='" + accountname
				+ "' and mobilephone='" + mobilephone + "' and hospitalcode='" + hospitalcode
				+ "' )or (accountname='winning' and mobilephone='winning' and hospitalcode='" + hospitalcode + "')) ";
		mSQLiteDatabase.execSQL(updatestate);
		cursor.close();
		mSQLiteDatabase.close();

	}

	// /双层listview注释下
	// private void initData(){
	// mSQLiteDatabase =
	// NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db",
	// MODE_PRIVATE, null);
	// String createtable =
	// " CREATE TABLE  if not exists WX_PUSH (xh  integer PRIMARY KEY autoincrement , "
	// + " title varchar(100)  ,message varchar(500)  ,apiKey varchar(100)  , "
	// +
	// "uri varchar(100) ,time varchar(30) ,type varchar(30) ,sfbc varchar(30) ,memo varchar(100))";
	// try {
	// mSQLiteDatabase.execSQL(createtable);
	// } catch (Exception e) {
	// System.out.println(e.getMessage());
	// }
	// try
	// {
	// JSONArray array = new JSONArray(data);
	// JSONObject jsonObject = null;
	// Map<String, Object> map = null;
	// for (int i = 0; i < array.length(); i++)
	// {
	// map = new HashMap<String, Object>();
	// jsonObject = array.getJSONObject(i);
	// map.put("name", jsonObject.getString("name"));
	// map.put("type", jsonObject.getString("type"));
	// map.put("child", getData(jsonObject.getString("type")));
	// grouplist.add(map);
	// }
	// }
	// catch (JSONException e)
	// {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// }

	// 获取ListView数据
	public List<Map<String, Object>> getData(String type)
	{
		// String type = intent.getStringExtra(Constants.NOTIFICATION_TYPE);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		String select = " SELECT xh,title,message,time FROM WX_PUSH where " + "type= '" + type + "' order by xh desc";
		Cursor cursor = mSQLiteDatabase.rawQuery(select, null);
		// 将光标移动到下一行，从而判断该结果集是否还有下一条数据，如果有则返回true，没有则返回false
		if (cursor != null && cursor.getCount() >= 0)
			while (cursor.moveToNext())
			{
				map = new HashMap<String, Object>();
				map.put("title", cursor.getString(cursor.getColumnIndex("title")));
				map.put("message", cursor.getString(cursor.getColumnIndex("message")));
				map.put("time", cursor.getString(cursor.getColumnIndex("time")));
				map.put("xh", cursor.getString(cursor.getColumnIndex("xh")));
				list.add(map);
			}
		cursor.close();
		mSQLiteDatabase.close();

		return list;
	}

	// private View createView(final String title, final String message,
	// final String uri)
	// {
	// LinearLayout linearLayout = new LinearLayout(this);
	// linearLayout.setBackgroundColor(0xffeeeeee);
	// linearLayout.setOrientation(LinearLayout.VERTICAL);
	// linearLayout.setPadding(5, 5, 5, 5);
	// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
	// LinearLayout.LayoutParams.FILL_PARENT,
	// LinearLayout.LayoutParams.FILL_PARENT);
	// linearLayout.setLayoutParams(layoutParams);
	//
	// TextView textTitle = new TextView(this);
	// textTitle.setText(title);
	// textTitle.setTextSize(18);
	// // textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
	// textTitle.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
	// textTitle.setTextColor(0xff000000);
	// textTitle.setGravity(Gravity.CENTER);
	//
	// layoutParams = new LinearLayout.LayoutParams(
	// LinearLayout.LayoutParams.FILL_PARENT,
	// LinearLayout.LayoutParams.WRAP_CONTENT);
	// layoutParams.setMargins(30, 30, 30, 0);
	// textTitle.setLayoutParams(layoutParams);
	// linearLayout.addView(textTitle);
	//
	// TextView textDetails = new TextView(this);
	// textDetails.setText(message);
	// textDetails.setTextSize(14);
	// // textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
	// textDetails.setTextColor(0xff333333);
	// textDetails.setGravity(Gravity.CENTER);
	//
	// layoutParams = new LinearLayout.LayoutParams(
	// LinearLayout.LayoutParams.FILL_PARENT,
	// LinearLayout.LayoutParams.WRAP_CONTENT);
	// layoutParams.setMargins(30, 10, 30, 20);
	// textDetails.setLayoutParams(layoutParams);
	// linearLayout.addView(textDetails);
	//
	// Button okButton = new Button(this);
	// okButton.setText("Ok");
	// okButton.setWidth(100);
	//
	// okButton.setOnClickListener(new View.OnClickListener()
	// {
	// public void onClick(View view)
	// {
	// Intent intent;
	// if (uri != null
	// && uri.length() > 0
	// && (uri.startsWith("http:") || uri.startsWith("https:")
	// || uri.startsWith("tel:") || uri.startsWith("geo:")))
	// {
	// intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
	// }
	// else
	// {
	// intent = new Intent().setClassName(callbackActivityPackageName,
	// callbackActivityClassName);
	// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	// intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
	// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
	// // intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
	// // intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
	// }
	// NotificationDetailsActivity.this.startActivity(intent);
	// NotificationDetailsActivity.this.finish();
	// }
	// });
	//
	// LinearLayout innerLayout = new LinearLayout(this);
	// innerLayout.setGravity(Gravity.CENTER);
	// innerLayout.addView(okButton);
	// linearLayout.addView(innerLayout);
	//
	// return linearLayout;
	// }

	public void savetohistory(int xh)
	{
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		// String droptable="drop table WX_PUSH_HISTORY";
		// try {
		// mSQLiteDatabase.execSQL(droptable);
		// } catch (Exception e) {
		// System.out.println(e.getMessage());
		// }
		String createtable = " CREATE TABLE  if not exists WX_PUSH_HISTORY (xh  integer PRIMARY KEY autoincrement , "
				+ " title varchar(100)  ,message varchar(500)  ,apiKey varchar(100)  , "
				+ "uri varchar(100) ,time varchar(30) ,memo varchar(100) ,user varchar(50),itime varchar(30))";
		String save = "insert into WX_PUSH_HISTORY(title,message,apiKey,uri,time,memo ,type,itime ) "
				+ "select title,message,apiKey,uri,time,memo,type," + "datetime(CURRENT_TIMESTAMP,'localtime') from WX_PUSH where xh="
				+ xh;

		try
		{
			mSQLiteDatabase.execSQL(createtable);
			mSQLiteDatabase.execSQL(save);
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		mSQLiteDatabase.close();
	}

	public void savealltohistory()
	{
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		// String droptable="drop table WX_PUSH_HISTORY";
		// try {
		// mSQLiteDatabase.execSQL(droptable);
		// } catch (Exception e) {
		// System.out.println(e.getMessage());
		// }
		String createtable = " CREATE TABLE  if not exists WX_PUSH_HISTORY (xh  integer PRIMARY KEY autoincrement , "
				+ " title varchar(100)  ,message varchar(500)  ,apiKey varchar(100)  , "
				+ "uri varchar(100) ,time varchar(30) ,memo varchar(100) ,type varchar(30),user varchar(50),itime varchar(30))";
		String save = "insert into WX_PUSH_HISTORY(title,message,apiKey,uri,time,memo ,type,itime ) "
				+ "select title,message,apiKey,uri,time,memo,type," + "datetime(CURRENT_TIMESTAMP,'localtime') from WX_PUSH ";
		try
		{
			mSQLiteDatabase.execSQL(createtable);
			mSQLiteDatabase.execSQL(save);
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		mSQLiteDatabase.close();
		print();
	}

	private boolean isJsonarray(Map map)
	{
		boolean flag = true;
		try
		{
			String json = '[' + map.get("message").toString() + ']';
			JSONArray array = new JSONArray(json);
			JSONObject jsonObject = array.getJSONObject(0);
			// jsonObject.getString("name");

			if (map.get("type").toString().equals("100"))
			{// 排队
				map.get("xh").toString();
				jsonObject.getString("type");
				jsonObject.getString("num");
				jsonObject.getString("lastNum");
				jsonObject.getString("weizhi");
				jsonObject.getString("time");
			}
			else if (map.get("type").toString().equals("200"))
			{// 挂号
				map.get("xh").toString();
				jsonObject.getString("fy");
				jsonObject.getString("time");
				jsonObject.getString("ysmc");
				jsonObject.getString("ghlx");
				jsonObject.getString("ks");
				jsonObject.getString("num");
				jsonObject.getString("dhrs");
			}
			else if (map.get("type").toString().equals("300"))
			{// 费用
				// {jfdz:'缴费地址：东三楼一楼大厅左侧',jfje:'150',items:[{name:'血生化',je:'98.5'},{name:'血常规',je:'30'},{name:'心电图',je:'21.5'}]}
				map.get("xh").toString();
				jsonObject.getString("jfdz");
				jsonObject.getString("jfje");

				JSONArray arrayitems = new JSONArray(jsonObject.getString("items"));

				// 费用明细
			}
			else if (map.get("type").toString().equals("301"))
			{// 费用
				// {jfdz:'缴费地址：东三楼一楼大厅左侧',jfje:'150',items:[{name:'血生化',je:'98.5'},{name:'血常规',je:'30'},{name:'心电图',je:'21.5'}]}
				map.get("xh").toString();
				jsonObject.getString("zyh");
				jsonObject.getString("bq");
				jsonObject.getString("zyrq");
				jsonObject.getString("dqrq");
				jsonObject.getString("je");
				JSONArray arrayitems = new JSONArray(jsonObject.getString("items"));

				// 费用明细
			}
			else if (map.get("type").toString().equals("400"))
			{// 导航
				// {dhbt:'检查结果已完成',dhdz:'东五楼',dhmdd:'检验窗口',dhmb:'处取检验报告'}

				map.get("xh").toString();

				jsonObject.getString("dhbt");
				jsonObject.getString("dhbt");
				jsonObject.getString("dhdz");
				jsonObject.getString("dhmdd");
				jsonObject.getString("dhmb");
			}
			else
			{// 其他提醒
				map.get("xh").toString();

			}
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag = false;

		}
		return flag;
	}

	public void print()
	{
		mSQLiteDatabase = NotificationDetailsActivity.this.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", MODE_PRIVATE, null);
		String select = " SELECT * FROM WX_PUSH_HISTORY order by xh desc";
		Cursor cursor = mSQLiteDatabase.rawQuery(select, null);
		// 将光标移动到下一行，从而判断该结果集是否还有下一条数据，如果有则返回true，没有则返回false
		if (cursor != null && cursor.getCount() >= 0)
			while (cursor.moveToNext())
			{
				System.out.println("message=" + cursor.getString(cursor.getColumnIndex("message")) + "time="
						+ cursor.getString(cursor.getColumnIndex("time")) + "itime=" + cursor.getString(cursor.getColumnIndex("itime"))
						+ "type=" + cursor.getString(cursor.getColumnIndex("type")));
			}
		cursor.close();
		mSQLiteDatabase.close();
	}

	public static Map<Integer, Boolean> isSelected;

	private class GroupAdapter extends BaseAdapter
	{

		private ItemsAdapter itemsAdapter;
		private ListView tempListView;

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return grouplist.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return grouplist.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			final Map<String, Object> map = (Map<String, Object>) getItem(position);

			try
			{
				String json = '[' + map.get("message").toString() + ']';
				JSONArray array = new JSONArray(json);
				JSONObject jsonObject = array.getJSONObject(0);
				// jsonObject.getString("name");

				if (map.get("type").toString().equals("100"))
				{// 排队
					view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.push_pd_item, null);
					TextView tv01 = (TextView) view.findViewById(R.id.push_pd_item_tv01);// 排队名（XX排队提醒）
					TextView tv02 = (TextView) view.findViewById(R.id.push_pd_item_tv04);// 当前号（您是XX号）
					TextView tv03 = (TextView) view.findViewById(R.id.push_pd_item_tv06);// 当前正在就诊号（29号正在就诊）
					TextView tv04 = (TextView) view.findViewById(R.id.push_pd_item_tv07);// 候诊位置（候诊位置：一号楼三楼302室）
					TextView tv05 = (TextView) view.findViewById(R.id.push_pd_item_tv08);// 预约就诊时间（预约就诊时间
					TextView senddate = (TextView) view.findViewById(R.id.push_pd_item_senddate);
					senddate.setText(map.get("senddate").toString());
					CheckBox push_pd_item_cb = (CheckBox) view.findViewById(R.id.push_pd_item_cb); // 12:35）
					push_pd_item_cb.setChecked(ls.contains(map.get("xh").toString()) ? true : false);
					push_pd_item_cb.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							if (((CheckBox) v).isChecked())
							{
								ls.add(map.get("xh").toString());
							}
							else
							{
								ls.remove(map.get("xh").toString());
							}
						}
					});
					tv01.setText(jsonObject.getString("type"));
					tv02.setText(jsonObject.getString("num"));
					tv03.setText(jsonObject.getString("lastNum"));
					tv04.setText(jsonObject.getString("weizhi"));
					tv05.setText(jsonObject.getString("time"));
				}
				else if (map.get("type").toString().equals("200"))
				{// 挂号
					view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.push_gh_item, null);
					TextView tv01 = (TextView) view.findViewById(R.id.push_gh_item_tv02); // 挂号费用(挂号费用XX元)
					TextView tv02 = (TextView) view.findViewById(R.id.push_gh_item_tv04);// 当前时间（）
					TextView tv03 = (TextView) view.findViewById(R.id.push_gh_item_tv05); // 医生名称
					TextView tv04 = (TextView) view.findViewById(R.id.push_gh_item_tv06);// 挂号类型
					TextView tv05 = (TextView) view.findViewById(R.id.push_gh_item_tv07);// 所挂科室
					TextView tv06 = (TextView) view.findViewById(R.id.push_gh_item_tv09);// 当前号(您是XX号)
					TextView tv07 = (TextView) view.findViewById(R.id.push_gh_item_tv12);// 前面有多少号（您前面还有XXX位在等候）
					TextView senddate = (TextView) view.findViewById(R.id.push_pd_item_senddate);
					senddate.setText(map.get("senddate").toString());
					CheckBox push_pd_item_cb = (CheckBox) view.findViewById(R.id.push_gh_item_cb); // 12:35）
					push_pd_item_cb.setChecked(ls.contains(map.get("xh").toString()) ? true : false);
					push_pd_item_cb.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							if (((CheckBox) v).isChecked())
							{
								ls.add(map.get("xh").toString());
							}
							else
							{
								ls.remove(map.get("xh").toString());
							}
						}
					});
					tv01.setText(jsonObject.getString("fy"));
					tv02.setText(jsonObject.getString("time"));
					tv03.setText(jsonObject.getString("ysmc"));
					tv04.setText(jsonObject.getString("ghlx"));
					tv05.setText(jsonObject.getString("ks"));
					tv06.setText(jsonObject.getString("num"));
					tv07.setText(jsonObject.getString("dhrs"));
				}
				else if (map.get("type").toString().equals("300"))
				{// 费用
					// {jfdz:'缴费地址：东三楼一楼大厅左侧',jfje:'150',items:[{name:'血生化',je:'98.5'},{name:'血常规',je:'30'},{name:'心电图',je:'21.5'}]}
					view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.push_fy_item, null);
					TextView tv01 = (TextView) view.findViewById(R.id.push_fy_item_tv01); // 缴费地址（缴费地址：东三楼一楼大厅左侧）
					TextView tv02 = (TextView) view.findViewById(R.id.push_fy_item_tv03);// 缴费金额（缴费金额XX元）
					TextView senddate = (TextView) view.findViewById(R.id.push_pd_item_senddate);
					senddate.setText(map.get("senddate").toString());
					CheckBox push_pd_item_cb = (CheckBox) view.findViewById(R.id.push_fy_item_cb); // 12:35）
					push_pd_item_cb.setChecked(ls.contains(map.get("xh").toString()) ? true : false);
					push_pd_item_cb.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							if (((CheckBox) v).isChecked())
							{
								ls.add(map.get("xh").toString());
							}
							else
							{
								ls.remove(map.get("xh").toString());
							}
						}
					});
					tv01.setText(jsonObject.getString("jfdz"));
					tv02.setText(jsonObject.getString("jfje"));
					Button zxff = (Button) view.findViewById(R.id.zxff);
					zxff.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							   // 拿到Fiap对象并传入容器  
//						      Fiap fiap = new Fiap(GhSix.this);  
//						      // 调用支付方法，并传入支付金额  
//						      fiap.android_pay(0.01); 
//							UtilPay pay=new UtilPay();  
//							pay.android_pay(0.01,oThis,"检查费用","检查费用");
							application.setStartDate(map.get("senddate").toString().substring(0, 10));
							application.setEndDate(map.get("senddate").toString().substring(0, 10));
							Intent intent = new Intent(oThis, CostMzSelect.class);
							startActivity(intent);
						}
					});
					JSONArray arrayitems = new JSONArray(jsonObject.getString("items"));
					List<Map<String, Object>> childs = new ArrayList<Map<String, Object>>();

					for (int j = 0; j < arrayitems.length(); j++)
					{
						JSONObject child = arrayitems.getJSONObject(j);
						childs.add(Utils.getMap(child.toString()));
					}

					tempListView = (ListView) view.findViewById(R.id.push_fy_item_list);
					itemsAdapter = new ItemsAdapter(childs);
					tempListView.setAdapter(itemsAdapter);
					setListViewHeightBasedOnChildren(tempListView);
					itemsAdapter.notifyDataSetChanged();
					// 费用明细
				}
				else if (map.get("type").toString().equals("301"))
				{// 费用
					// {jfdz:'缴费地址：东三楼一楼大厅左侧',jfje:'150',items:[{name:'血生化',je:'98.5'},{name:'血常规',je:'30'},{name:'心电图',je:'21.5'}]}
					view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.push_yrqd_item, null);
					TextView tv01 = (TextView) view.findViewById(R.id.push_yrqd_item_tv01); // 缴费地址（缴费地址：东三楼一楼大厅左侧）
					TextView tv02 = (TextView) view.findViewById(R.id.push_yrqd_item_tv02);// 缴费金额（缴费金额XX元）
					TextView tv03 = (TextView) view.findViewById(R.id.push_yrqd_item_tv03);// 缴费金额（缴费金额XX元）
					TextView tv04 = (TextView) view.findViewById(R.id.push_yrqd_item_tv04);// 缴费金额（缴费金额XX元）
					TextView tv05 = (TextView) view.findViewById(R.id.push_yrqd_item_tv05);// 缴费金额（缴费金额XX元）
					TextView tv06 = (TextView) view.findViewById(R.id.push_yrqd_item_tv06);// 缴费金额（缴费金额XX元）
					TextView tv07 = (TextView) view.findViewById(R.id.push_yrqd_item_tv07);// 缴费金额（缴费金额XX元）
					TextView tv08 = (TextView) view.findViewById(R.id.push_yrqd_item_tv08);// 缴费金额（缴费金额XX元）
					CheckBox push_pd_item_cb = (CheckBox) view.findViewById(R.id.push_yrqd_item_cb); // 12:35）
					TextView senddate = (TextView) view.findViewById(R.id.push_pd_item_senddate);
					senddate.setText(map.get("senddate").toString());
					push_pd_item_cb.setChecked(ls.contains(map.get("xh").toString()) ? true : false);
					push_pd_item_cb.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							if (((CheckBox) v).isChecked())
							{
								ls.add(map.get("xh").toString());
							}
							else
							{
								ls.remove(map.get("xh").toString());
							}
						}
					});
					tv01.setText(jsonObject.getString("zyh"));
					tv02.setText(jsonObject.getString("bq"));
					tv03.setText(jsonObject.getString("zyrq"));
					tv05.setText(jsonObject.getString("dqrq"));
					tv07.setText(jsonObject.getString("je"));
					Button zxff = (Button) view.findViewById(R.id.zxff);
					zxff.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							   // 拿到Fiap对象并传入容器  
//						      Fiap fiap = new Fiap(GhSix.this);  
//						      // 调用支付方法，并传入支付金额  
//						      fiap.android_pay(0.01); 
//							UtilPay pay=new UtilPay();  
//							pay.android_pay(0.01,oThis,"检查费用","检查费用");
							application.setStartDate(map.get("senddate").toString().substring(0, 10));
							application.setEndDate(map.get("senddate").toString().substring(0, 10));
							Intent intent = new Intent(oThis, CostMzSelect.class);
							startActivity(intent);
						}
					});
					JSONArray arrayitems = new JSONArray(jsonObject.getString("items"));
					List<Map<String, Object>> childs = new ArrayList<Map<String, Object>>();

					for (int j = 0; j < arrayitems.length(); j++)
					{
						JSONObject child = arrayitems.getJSONObject(j);
						childs.add(Utils.getMap(child.toString()));
					}

					tempListView = (ListView) view.findViewById(R.id.push_yrqd_item_list);
					itemsAdapter = new ItemsAdapter(childs);
					tempListView.setAdapter(itemsAdapter);
					setListViewHeightBasedOnChildren(tempListView);
					itemsAdapter.notifyDataSetChanged();
					// 费用明细
				}
				else if (map.get("type").toString().equals("400"))
				{// 导航
					// {dhbt:'检查结果已完成',dhdz:'东五楼',dhmdd:'检验窗口',dhmb:'处取检验报告'}
					view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.push_dh_item, null);
					TextView tv01 = (TextView) view.findViewById(R.id.push_dh_item_tv01); // 导航标题（检查结果已完成）
					TextView tv02 = (TextView) view.findViewById(R.id.push_dh_item_tv02);// 导航标题（检查结果已完成，请到）
					TextView tv03 = (TextView) view.findViewById(R.id.push_dh_item_tv03); // 导航地址
																																								// （东五楼）
					TextView tv04 = (TextView) view.findViewById(R.id.push_dh_item_tv04); // 导航目的地（检验窗口）
					TextView tv05 = (TextView) view.findViewById(R.id.push_dh_item_tv05); // 导航目标（处取检验报告）
					TextView senddate = (TextView) view.findViewById(R.id.push_pd_item_senddate);
					senddate.setText(map.get("senddate").toString());
					CheckBox push_pd_item_cb = (CheckBox) view.findViewById(R.id.push_dh_item_cb); // 12:35）
					push_pd_item_cb.setChecked(ls.contains(map.get("xh").toString()) ? true : false);
					push_pd_item_cb.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							if (((CheckBox) v).isChecked())
							{
								ls.add(map.get("xh").toString());
							}
							else
							{
								ls.remove(map.get("xh").toString());
							}
						}
					});
					tv01.setText(jsonObject.getString("dhbt"));
					tv02.setText(jsonObject.getString("dhbt") + ",请到");
					tv03.setText(jsonObject.getString("dhdz"));
					tv04.setText(jsonObject.getString("dhmdd"));
					tv05.setText(jsonObject.getString("dhmb"));
				}
				else
				{// 其他提醒
					view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.push_tx_item, null);

					TextView tv01 = (TextView) view.findViewById(R.id.push_tx_item_tv01);// 提醒标题
					TextView tv02 = (TextView) view.findViewById(R.id.push_tx_item_tv02);// 提醒时间
					TextView tv03 = (TextView) view.findViewById(R.id.push_tx_item_tv03);// 提醒内容
					TextView senddate = (TextView) view.findViewById(R.id.push_pd_item_senddate);
					senddate.setText(map.get("senddate").toString());
					CheckBox push_pd_item_cb = (CheckBox) view.findViewById(R.id.push_tx_item_cb); // 12:35）
					push_pd_item_cb.setChecked(ls.contains(map.get("xh").toString()) ? true : false);
					push_pd_item_cb.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							if (((CheckBox) v).isChecked())
							{
								ls.add(map.get("xh").toString());
							}
							else
							{
								ls.remove(map.get("xh").toString());
							}
						}
					});
					tv01.setText((CharSequence) map.get("title").toString());
					tv02.setText((CharSequence) map.get("time").toString());
					tv03.setText(jsonObject.getString("message"));

				}
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();

			}

			// List<Map<String, Object>> childlist = new ArrayList<Map<String,
			// Object>>();
			// try
			// {
			//
			// childlist = (List) map.get("child");
			// tempListView = (ListView) view.findViewById(R.id.push_items_list);
			// itemsAdapter = new ItemsAdapter(childlist);
			// tempListView.setAdapter(itemsAdapter);
			// setListViewHeightBasedOnChildren(tempListView);
			// itemsAdapter.notifyDataSetChanged();
			// }
			// catch (Exception e)
			// {
			//
			// }

			return view;
		}

	}

	// 根据子项的高度重新设定主listview的item项高度
	public static void setListViewHeightBasedOnChildren(ListView listView)
	{
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null)
		{
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++)
		{
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	private class ItemsAdapter extends BaseAdapter
	{
		private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		public ItemsAdapter(List<Map<String, Object>> templist)
		{
			list = templist;
		}

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.push_item_list, null);
			TextView tv01 = (TextView) view.findViewById(R.id.push_items_list_tv_01);
			TextView tv02 = (TextView) view.findViewById(R.id.push_items_list_tv_03);
			tv01.setText((CharSequence) map.get("name").toString());
			tv02.setText((CharSequence) map.get("je").toString());
			return view;
		}

	}

	// class MyAdapter extends BaseAdapter {
	// private class MyHolder {
	// TextView title;
	// TextView message;
	// TextView time;
	// CheckBox myCheckBox;
	// }
	//
	// List<Boolean> mChecked;
	// private Context context;
	// List<Map<String, Object>> list;
	// HashMap<Integer, View> map = new HashMap<Integer, View>();
	// // List<Map<String, Object>> selected;
	// private LayoutInflater mInflater;
	//
	// public MyAdapter(Context context, List<Map<String, Object>> list) {
	// super();
	// this.context = context;
	// this.list = list;
	// mInflater = (LayoutInflater) context
	// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	// mChecked = new ArrayList<Boolean>();
	//
	// for (int i = 0; i < list.size(); i++) {
	// mChecked.add(false);
	// }
	//
	// }
	//
	// @Override
	// public int getCount() {
	// // TODO Auto-generated method stub
	// return list.size();
	// }
	//
	// @Override
	// public Object getItem(int index) {
	// // TODO Auto-generated method stub
	// return list.get(index);
	//
	// }
	//
	// @Override
	// public long getItemId(int position) {
	// // TODO Auto-generated method stub
	// return position;
	// }
	//
	// @Override
	// public View getView(int position, View convertView, ViewGroup parent) {
	// // TODO Auto-generated method stub
	// final MyHolder holder;
	// if (convertView == null) {
	// if (mInflater == null) {
	// mInflater = (LayoutInflater)
	// NotificationDetailsActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
	// }
	// convertView = mInflater.inflate(R.layout.push_list, null);
	// holder = new MyHolder();
	// holder.title = (TextView) convertView.findViewById(R.id.title);
	// holder.message = (TextView) convertView
	// .findViewById(R.id.message);
	// holder.time = (TextView) convertView.findViewById(R.id.time);
	//
	// holder.myCheckBox = (CheckBox) convertView.findViewById(R.id.checkBoxEdit);
	// final int p = position;
	//
	// map.put(position, convertView);
	//
	// holder.myCheckBox
	// .setOnClickListener(new View.OnClickListener() {
	// @Override
	// public void onClick(View v) {
	// CheckBox cb = (CheckBox) v;
	// mChecked.set(p, cb.isChecked());
	// }
	// });
	//
	// convertView.setTag(holder);
	// } else {
	// holder = (MyHolder) convertView.getTag();
	// }
	// Map<String, Object> hjInfo = list.get(position);
	// holder.title.setText(hjInfo.get("title").toString());
	// holder.message.setText(hjInfo.get("message").toString());
	// holder.time.setText(hjInfo.get("time").toString().substring(6, 16));
	// holder.myCheckBox.setChecked(mChecked.get(position));
	// // setHolder(position, holder);
	// return convertView;
	// }
	//
	// public List<Map<String, Object>> getList() {
	// return list;
	// }
	//
	// }

}
